import json
import time

import requests
from lxml import etree


def login_get_cookie(s_num, pwd):
    """
    输入学号、密码获取cookie，模拟登录状态
    :param s_num: 学号
    :param pwd: 密码
    :return: cookie字符串
    """
    url = "http://newjw.cduestc.cn:1234/loginAction.do"
    data = {
        "zjh": s_num,
        "mm": pwd
    }
    res = requests.post(url, data)
    cookie_dict = requests.utils.dict_from_cookiejar(res.cookies)
    for key, v in cookie_dict.items():
        if key == "JSESSIONID":
            return key + "=" + v


def get_teach_list(cookie, is_teach=False):
    """
    获取评教列表
    :param cookie: cookie
    :param is_teach: false未进行评教， true已评教
    :return: 查询列表
    """
    url = "http://newjw.cduestc.cn:1234/jxpgXsAction.do?oper=listWj"
    header = {
        "cookie": cookie
    }
    res = requests.get(url, headers=header)
    html = etree.HTML(res.text)
    trs = html.xpath("//tr[@class='odd']")
    is_teach = "是" if is_teach else "否"
    res_list = list()
    for tr in trs:
        need_to_teach = dict()
        if tr[3].xpath("./text()")[0] == is_teach:
            need_to_teach['title'] = tr[0].xpath("./text()")[0]
            need_to_teach['name'] = tr[1].xpath("./text()")[0]
            need_to_teach['subject'] = tr[2].xpath("./text()")[0]
            need_to_teach['isTeach'] = tr[3].xpath("./text()")[0]
            params = str(tr[4].xpath(".//img/@name")[0]).split("#@")
            need_to_teach['params'] = {
                "wjbm": str(params[0]),
                "bpr": str(params[1]),
                "pgnr": str(params[5]),
                "wjmc": str(params[3]),
                "bprm": str(params[2]),
                "pgnrm": str(params[4])
            }
            res_list.append(need_to_teach)
    return res_list


def teach(cookie, need_teach_list=None):
    """
    评教操作
    :param cookie: cookie
    :param need_teach_list: 需要评教的列表
    :return: none
    """
    url = "http://newjw.cduestc.cn:1234/jxpgXsAction.do"
    teach_url = "http://newjw.cduestc.cn:1234/jxpgXsAction.do?oper=wjpg"
    header = {
        "Content-Type": "application/x-www-form-urlencoded",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
        "cookie": cookie
    }
    res_list = list()
    for item in need_teach_list:
        data = item.get("params")
        data['oper'] = "wjShow"
        res = requests.post(url, data=data, headers=header)
        html = etree.HTML(res.text)
        inputs = html.xpath("//input[@type='radio']")
        item = ""
        req_param = {
            'wjbm': data['wjbm'],
            'bpr': data['bpr'],
            'pgnr': data['pgnr']
        }
        print("正在评教：《{}》，教师：{}".format(data["pgnrm"],data["bprm"]))
        for input in inputs:
            if item == input.xpath(".//@name")[0]:
                continue
            item = input.xpath(".//@name")[0]
            req_param[item] = input.xpath(".//@value")[0]
            req_param['zgpj'] = "课程内容充实，课堂时间安排合理。".encode("gb2312")
            # print(input.xpath(".//@name")[0], input.xpath(".//@value")[0])
            time.sleep(0.2)
        # print("req_param", req_param)
        requests.post(teach_url, data=req_param, headers=header)
        # print(res.text)
        res_list.append(req_param)
    return res_list


if __name__ == '__main__':
    try:
        s_num = input("请输入学号：")
        pwd = input("请输入密码：")
        print("正在进行登录......")
        time.sleep(0.2)
        cookie = login_get_cookie(s_num, pwd)
        time.sleep(0.2)
        print("登录成功！正在获取未评教列表....")
        time.sleep(0.3)
        to_teach = get_teach_list(cookie)
        if to_teach:
            time.sleep(0.2)
            print("未评教课程：", [i.get("subject") for i in to_teach])
            print("请稍等，正在自动评教.....")
            teach(cookie, to_teach)
            time.sleep(0.5)
            print("评教成功，已评教课程：\n", [i.get("subject") for i in get_teach_list(cookie, True)])
        else:
            print("你暂时没有未进行评教的课程！")
            print("已评教课程：\n", [i.get("subject") for i in get_teach_list(cookie, True)])
        print("评教结束，请返回教务系统确认！")
    except:
        print("暂时不能评教")
